//
//  Album.swift
//  GhostWorld
//
//  Created by Kam on 2018/4/3.
//  Copyright © 2018 LKGood. All rights reserved.
//

import Foundation
import CoreData

private let albumEntityName = CoreDataEntityName.album.rawValue
private let audioEntityName = CoreDataEntityName.audio.rawValue
private let context = CoreDataHelper.getContext()

extension Album {
  
  enum DefaultAlbumIdentifer: Int {
    case yingLiuYan = 10022
    case zaiRenJian = 10023
    case guiYinChongChong = 10202
    case anGe = 52
  }
  
  var cover: RemoteImage {
    get {
      return RemoteImage(origianlPath: coverOriginal, mediumPath: nil, thumbPath: coverThumb)
    }
  }
  
  var group: Group? {
    get {
      let id = Int(groupID)
      return EntityManager.fetch(Group.self, fetchType: .id(id))?.first
    }
  }
  
  var audios: [Audio]? {
    get {
      let request = NSFetchRequest<Audio>()
      request.entity = NSEntityDescription.entity(forEntityName: audioEntityName, in: context)
      request.predicate = NSPredicate(format: "albumID = %@", "\(id)")
      request.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)]
      
      do {
        let audios = try context.fetch(request)
        return audios
      } catch let error {
        loggingPrint(error)
        return nil
      }
    }
  }
  
  var downloadedAudios: [Audio]? {
    return audios?.filter { $0.localURL != nil }
  }
  
  var downloadedAudioFileSizeInMegaBytes: Float {
    if let audios = downloadedAudios {
      let size: Float = audios.reduce(0.0) {
        $0 + $1.cacheFileSizeInMegaBytes
      }
      return size
    } else {
      return 0
    }
  }
  
  public override var description: String {
    var childrenString = ""
    if let children = self.audios {
      childrenString = children.map {
        "\($0.id)"
        }.joined(separator: ",")
    }
    return "[Album] id: \(id), name: \(name ?? "--"), group: \(group != nil ? "\(group!.id)" : "nil"), audiosCount:(\(audioCount), audios: \(childrenString.count > 0 ? childrenString : "nil")"
  }
  
  func getShortDescription(length: Int) -> String {
    guard length > 0 else {
      return "--"
    }
    
    if let description = albumDescription {
      if description.count < length {
        return description
      } else {
        return description.substring(to: length) + "..."
      }
    } else {
      return "--"
    }
  }
  
  func updateAudioSortType(_ sortType: AudioSortType) throws {
    audioSortType = Int16(sortType.rawValue)
    do {
      try context.save()
    } catch let error {
      loggingPrint("Update album audios sort type failed. \(error.localizedDescription)")
      throw error
    }
  }
}
